package com.tony.mindhr.config;

import com.tony.mindhr.model.Menu;
import com.tony.mindhr.model.Role;
import com.tony.mindhr.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: MyFilter
 * @Auther: 皮蛋布丁
 * @Date: 2021/05/17/20:52
 * @Description: 01根据用户传来的请求地址，分析出请求需要的角色(启动权限访问)
 */
@Component
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    MenuService menuService;
    //比对工具
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        //当前请求地址
        String requestUrl = ((FilterInvocation) o).getRequestUrl();

        List<Menu> menus = menuService.getAllMenusWithRole();
        for (Menu menu : menus) {
            //antPathMatcher.match(匹配的规则，需要被匹配的数据)
            if (antPathMatcher.match(menu.getUrl(),requestUrl)) {
                List<Role> roles = menu.getRoles();
                String[]  str = new String[roles.size()];
                for (int i = 0; i < roles.size(); i++) {
                    str[i] = roles.get(i).getName();
                }
                //将role转化为返回的类型
                return SecurityConfig.createList(str);
            }
        }
        //未匹配的，统一登录即可访问(传递一个标记)
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
